package luke4fun.wheresmymoney.fragments;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.common.CommonConstants;
import luke4fun.wheresmymoney.util.DateUtil;

public class StatisticFragmentPagerAdapter extends FragmentStatePagerAdapter {

	List<Fragment> fragments = new ArrayList<Fragment>(3);
	private long dateInMillis = DateUtil.getCurrentMonthInMillis();
	
	public StatisticFragmentPagerAdapter(FragmentManager fm) {
		super(fm);
		
		long prev  = DateUtil.getPrevMonthInMillis(dateInMillis);
		long prev2 = DateUtil.getPrevMonthInMillis(prev);
		fragments.add(MonthStatisticFragment.getInstance(prev2));
		fragments.add(MonthStatisticFragment.getInstance(prev));
		fragments.add(MonthStatisticFragment.getInstance(dateInMillis));
	}
	
	public long getDateInMillis() {
		return this.dateInMillis;
	}

	@Override
	public Fragment getItem(int position) {
		return fragments.get(position);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}
	
	@Override
	public int getItemPosition(Object item) {
		return POSITION_NONE;
	}
	
	@Override
    public CharSequence getPageTitle(int position) {
		String title = "";
        return title;
    }
	
	public boolean move(int direction) {
		boolean changed = false;
		if (direction == CommonConstants.SHIFT_LEFT) {
			long newMillis = DateUtil.getNextMonthInMillis(fragments.get(2).getArguments().getLong(CommonConstants.ARG_DATE));
			
			if (newMillis <= CommonConstants.CURRENT_MONTH) {
				fragments.set(0, fragments.get(1));
				fragments.set(1, fragments.get(2));
				dateInMillis = fragments.get(1).getArguments().getLong(CommonConstants.ARG_DATE);
				fragments.set(2, MonthStatisticFragment.getInstance(newMillis));
				changed = true;
			}
		} else if (direction == CommonConstants.SHIFT_RIGHT) {
			long newMillis = DateUtil.getPrevMonthInMillis(fragments.get(0).getArguments().getLong(CommonConstants.ARG_DATE));

			if (newMillis >= CommonConstants.LEFT_LIMIT_MONTH) {  
				fragments.set(2, fragments.get(1));
				fragments.set(1, fragments.get(0));
				dateInMillis = fragments.get(1).getArguments().getLong(CommonConstants.ARG_DATE);
				fragments.set(0, MonthStatisticFragment.getInstance(newMillis));
				changed = true;
			}
		}
		
		notifyDataSetChanged();
		return changed;
	}
}
